<template>
  <div class="main">
    <!-- 顶部标题栏 -->
    <div class="header-section">
      <div class="stock-header">
        <div class="stock-info">
          <div class="stock-title">
            <h1 class="ticker-symbol">{{ stockSymbol }}</h1>
            <div class="stock-subtitle">实时行情 · LIVE</div>
          </div>
          <div class="market-info">
            <div class="market-status">
              <span class="status-dot"></span>
              <span class="status-text">开盘中</span>
            </div>
            <div class="market-time">{{ currentTime }}</div>
          </div>
        </div>
        <div class="header-actions">
          <div class="quick-stats">
            <div class="stat-item">
              <span class="stat-label">成交量</span>
              <span class="stat-value">{{ formatVolume(volume) }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">市值</span>
              <span class="stat-value">{{ formatMarketCap(marketCap) }}</span>
            </div>
          </div>
          <div class="action-buttons">
            <button @click="toggleFavorite" class="favorite-btn" :class="{ favorited: isFavorited }">
              <span>{{ isFavorited ? '已收藏' : '收藏' }}</span>
            </button>
            <button @click="reload" class="reload-btn">
              <span>刷新</span>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要价格显示 -->
    <div class="main-price-section">
      <div class="primary-price">
        <div class="current-price-large">
          <span class="currency-symbol">¥</span>
          <span class="price-number">{{ currentPrice }}</span>
          <div class="price-change" :class="getPriceChangeClass()">
            <span class="change-amount">{{ priceChange }}</span>
            <span class="change-percent">({{ priceChangePercent }}%)</span>
          </div>
        </div>
        <div class="price-details">
          <div class="detail-row">
            <span class="detail-label">开盘:</span>
            <span class="detail-value">¥{{ openPrice }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">收盘:</span>
            <span class="detail-value">¥{{ prevClose }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 价格统计网格 -->
    <div class="price-stats-grid">
      <div class="stat-card">
        <div class="stat-header">
          <span class="stat-title">24H最高</span>
        </div>
        <div class="stat-value high-price">¥{{ dayHigh }}</div>
        <div class="stat-change positive">+{{ ((dayHigh - currentPrice) / currentPrice * 100).toFixed(2) }}%</div>
      </div>

      <div class="stat-card">
        <div class="stat-header">
          <span class="stat-title">24H最低</span>
        </div>
        <div class="stat-value low-price">¥{{ dayLow }}</div>
        <div class="stat-change negative">{{ ((dayLow - currentPrice) / currentPrice * 100).toFixed(2) }}%</div>
      </div>

      <div class="stat-card">
        <div class="stat-header">
          <span class="stat-title">成交量</span>
        </div>
        <div class="stat-value volume-number">{{ formatVolume(volume) }}</div>
        <div class="stat-change neutral">24H</div>
      </div>

      <div class="stat-card">
        <div class="stat-header">
          <span class="stat-title">振幅</span>
        </div>
        <div class="stat-value amplitude-number">{{ calculateAmplitude() }}%</div>
        <div class="stat-change neutral">今日</div>
      </div>

      <div class="stat-card">
        <div class="stat-header">
          <span class="stat-title">换手率</span>
        </div>
        <div class="stat-value turnover-rate">{{ turnoverRate }}%</div>
        <div class="stat-change neutral">活跃度</div>
      </div>

      <div class="stat-card">
        <div class="stat-header">
          <span class="stat-title">市盈率</span>
        </div>
        <div class="stat-value pe-ratio">{{ peRatio }}</div>
        <div class="stat-change neutral">TTM</div>
      </div>
    </div>

    <!-- K线图表区域 -->
    <div class="chart-container">
      <div class="chart-header">
        <div class="chart-title-section">
          <h3>K线图表</h3>
        </div>
        <div class="chart-controls">
          <div class="timeframe-tabs">
            <button class="time-btn active">15分钟</button>
            <button class="time-btn">1小时</button>
            <button class="time-btn">日线</button>
          </div>
        </div>
      </div>
      <div ref="chartRef" class="k-chart">
        <div class="chart-overlay">
          <div class="market-status">
            <span class="status-text">交易中</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 专业交易面板 -->
    <div class="trading-section">
      <div class="section-header">
        <div class="header-left">
          <h3>交易</h3>
        </div>
        <div class="header-right">
          <div class="account-balance" v-if="hasToken">
            <span class="balance-label">可用资金</span>
            <span class="balance-amount">¥{{ accountBalance }}</span>
          </div>
        </div>
      </div>

      <div class="toolbar-tabs">
        <button
            :class="['tab-btn', { active: activeTab === 'order' }]"
            @click="activeTab = 'order'"
        >
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/>
            <rect x="8" y="2" width="8" height="4" rx="1" ry="1"/>
          </svg>
          <span>委托下单</span>
        </button>
        <button
            :class="['tab-btn', { active: activeTab === 'history' }]"
            @click="activeTab = 'history'"
        >
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <path d="M3 3h18v18H3zM21 9H3"/>
            <path d="M9 21V9"/>
          </svg>
          <span>历史委托</span>
        </button>
      </div>

      <!-- 委托面板 -->
      <div v-if="activeTab === 'order'" class="panel-content">
        <div v-if="!hasToken" class="login-prompt">
          <div class="login-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/>
              <polyline points="10,17 15,12 10,7"/>
              <line x1="15" y1="12" x2="3" y2="12"/>
            </svg>
          </div>
          <h3>登录后开始交易</h3>
          <p>登录您的账户以开始股票委托交易</p>
          <button @click="goToLogin" class="login-btn">
            立即登录
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <path d="m9 18 6-6-6-6"/>
            </svg>
          </button>
        </div>

        <div v-else class="order-form">
          <!-- 交易类型选择 -->
          <div class="trade-type-section">
            <h4>选择交易类型</h4>
            <div class="order-type">
              <label :class="{ active: orderType === 'buy' }">
                <input type="radio" v-model="orderType" value="buy" />
                <div class="radio-content">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                    <path d="M7 17L17 7"/>
                    <path d="M7 7h10v10"/>
                  </svg>
                  <span>买入</span>
                </div>
              </label>
              <label :class="{ active: orderType === 'sell' }">
                <input type="radio" v-model="orderType" value="sell" />
                <div class="radio-content">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                    <path d="M17 7L7 17"/>
                    <path d="M17 17H7V7"/>
                  </svg>
                  <span>卖出</span>
                </div>
              </label>
            </div>
          </div>

          <!-- 交易信息输入 -->
          <div class="trade-inputs-section">
            <h4>交易信息</h4>
            <div class="order-inputs">
              <div class="input-group">
                <label>委托价格</label>
                <div class="input-wrapper">
                  <span class="input-prefix">¥</span>
                  <input
                      v-model="orderPrice"
                      type="number"
                      :placeholder="currentPrice"
                      step="0.01"
                  />
                  <button class="quick-fill" @click="orderPrice = currentPrice">
                    市价
                  </button>
                </div>
              </div>
              <div class="input-group">
                <label>委托数量</label>
                <div class="input-wrapper">
                  <input
                      v-model="orderAmount"
                      type="number"
                      placeholder="请输入数量"
                      step="1"
                  />
                  <span class="input-suffix">股</span>
                </div>
              </div>
            </div>

            <!-- 预计金额 -->
            <div class="order-summary" v-if="orderPrice && orderAmount">
              <div class="summary-row">
                <span>预计金额</span>
                <span class="summary-value">¥{{ (orderPrice * orderAmount).toFixed(2) }}</span>
              </div>
              <div class="summary-row">
                <span>手续费</span>
                <span class="summary-value">¥{{ (orderPrice * orderAmount * 0.001).toFixed(2) }}</span>
              </div>
            </div>
          </div>

          <!-- 提交按钮 -->
          <button @click="submitOrder" class="submit-btn" :class="orderType">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
              <polyline points="22,4 12,14.01 9,11.01"/>
            </svg>
            <span>{{ orderType === 'buy' ? '确认买入' : '确认卖出' }}</span>
          </button>
        </div>
      </div>

      <!-- 历史委托面板 -->
      <div v-if="activeTab === 'history'" class="panel-content">
        <div v-if="!hasToken" class="login-prompt">
          <div class="login-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <path d="M9 12l2 2 4-4"/>
              <path d="M21 12c0 4.97-4.03 9-9 9s-9-4.03-9-9 4.03-9 9-9c2.38 0 4.53.94 6.12 2.47"/>
            </svg>
          </div>
          <h3>查看历史委托</h3>
          <p>登录后查看您的所有历史交易记录</p>
          <button @click="goToLogin" class="login-btn">
            立即登录
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <path d="m9 18 6-6-6-6"/>
            </svg>
          </button>
        </div>

        <div v-else class="history-content">
          <div class="history-header">
            <h4>历史委托记录</h4>
            <div class="history-filters">
              <select class="filter-select" v-model="statusFilter">
                <option value="">全部</option>
                <option value="done">已成交</option>
                <option value="ing">待成交</option>
                <option value="cancel">已撤销</option>
              </select>
            </div>
          </div>

          <div class="history-list">
            <div v-if="filteredOrderHistory.length === 0" class="empty-history">
              <div class="empty-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                  <path d="M9 11H5a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2v-7a2 2 0 0 0-2-2h-1M9 11V9a4 4 0 1 1 8 0v2m-8 0h8m0 0v2a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2v-2"/>
                </svg>
              </div>
              <h4>暂无委托记录</h4>
              <p>您还没有进行过任何委托交易</p>
            </div>

            <div v-else class="history-item" v-for="order in filteredOrderHistory" :key="order.orderId">
              <div class="order-main">
                <div class="order-type-badge" :class="order.buySell">
                  <svg v-if="order.buySell === 'buy'" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                    <path d="M7 17L17 7"/>
                    <path d="M7 7h10v10"/>
                  </svg>
                  <svg v-else viewBox="0 0 24 24" fill="none" stroke="currentColor">
                    <path d="M17 7L7 17"/>
                    <path d="M17 17H7V7"/>
                  </svg>
                  <span>{{ order.buySell === 'buy' ? '买入' : '卖出' }}</span>
                </div>
                <div class="order-details">
                  <div class="order-symbol">{{ order.stockSymbol }}</div>
                  <div class="order-price-amount">
                    <span class="order-price">¥{{ order.orderAmount }}</span>
                    <span class="order-amount">{{ order.stockQuantity }}股</span>
                  </div>
                  <div class="order-total">
                    <span>总金额: ¥{{ order.orderAllAmount }}</span>
                  </div>
                  <div class="order-time">{{ formatDate(order.createdAt) }}</div>
                </div>
              </div>
              <div class="order-status" :class="order.status">
                <span class="status-text">{{ getStatusText(order.status) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { onMounted, onUnmounted, ref, computed, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {getStockMes} from "@/api/stock/stocks";
import { useTokenStore } from '@/stores/token.js'
// eslint-disable-next-line
import {pushBuyOrder,pushSellOrder} from "@/api/market/order";
const route = useRoute()
const router = useRouter()
const tokenStore = useTokenStore()

const chartRef = ref(null)
let chart = null
// eslint-disable-next-line no-unused-vars
let timer = null

// 从路由参数获取 stockSymbol
const stockSymbol = ref(route.query.stockSymbol)

// 价格相关数据
const currentPrice = ref('0.00')
const dayLow = ref('0.00')
const dayHigh = ref('0.00')
const openPrice = ref('0.00')
const prevClose = ref('0.00')
const priceChange = ref('0.00')
const priceChangePercent = ref('0.00')
const volume = ref(1234567)
const marketCap = ref(89765432100)
const turnoverRate = ref('3.45')
const peRatio = ref('24.5')
const currentTime = ref('')

// 技术指标数据
const ma5 = ref('0.00')
const ma10 = ref('0.00')
const ma20 = ref('0.00')
const macd = ref('0.00')
const macdClass = ref('positive')

// 更新时间
const updateCurrentTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleTimeString('zh-CN', {
    hour12: false,
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 委托相关数据
const activeTab = ref('order')
const orderType = ref('buy')
const orderPrice = ref('')
const orderAmount = ref('')
const orderHistory = ref([])
const statusFilter = ref('')
const accountBalance = ref('')

// 收藏功能
const isFavorited = ref(false)

// 计算是否有token
const hasToken = computed(() => {
  return !!tokenStore.token
})

// 过滤后的历史委托
const filteredOrderHistory = computed(() => {
  if (!statusFilter.value) {
    return orderHistory.value
  }
  return orderHistory.value.filter(order => order.status === statusFilter.value)
})

const fullKData = ref([])         // 全部 K 线数据
const timeLabelsAll = ref([])     // 全部时间标签
const currentIndex = ref(getTodayKey())       // 当前key

function getTodayKey() {
  const todayStr = new Date().toISOString().split('T')[0] // 例如 "2025-04-19"
  const savedDate = localStorage.getItem('kline_date')
  let key = parseInt(localStorage.getItem('kline_key') || '1')

  if (savedDate !== todayStr) {
    // 日期变了，说明新的一天，key 自增
    key += 1
    localStorage.setItem('kline_key', key.toString())
    localStorage.setItem('kline_date', todayStr)
  }

  return key
}

// 获取数据但不渲染，保存到 fullKData、timeLabelsAll
async function prepareKLineData() {
  try {
    const data = []
    const timeLabels = []
    const startTime = new Date()
    startTime.setHours(0, 0, 0, 0)

    const msg = {"stockSymbol": stockSymbol.value}
    const {data: response} = await getStockMes(msg)

    // 检查响应数据
    if (!response || response.length === 0) {
      console.error('No data received from API, using test data')
      // 使用测试数据
      const testData = []
      for (let i = 0; i < 96; i++) { // 24小时 * 4个点/小时
        const basePrice = 100 + Math.random() * 20
        const open = basePrice
        const close = basePrice + (Math.random() - 0.5) * 10
        const high = Math.max(open, close) + Math.random() * 5
        const low = Math.min(open, close) - Math.random() * 5
        testData.push(open, high, low, close)
      }
      // eslint-disable-next-line
      response = testData
    }

    for (let i = 0; i < response.length; i += 4) {
      const open = response[i]
      const close = response[i + 3]
      const high = Math.max(response[i], response[i + 1], response[i + 2], response[i + 3])
      const low = Math.min(response[i], response[i + 1], response[i + 2], response[i + 3])
      data.push([open, close, low, high])

      const labelTime = new Date(startTime.getTime() + (i / 4) * 15 * 60 * 1000)
      const hour = labelTime.getHours().toString().padStart(2, '0')
      const min = labelTime.getMinutes().toString().padStart(2, '0')
      timeLabels.push(`${hour}:${min}`)
    }

    fullKData.value = data
    timeLabelsAll.value = timeLabels
    currentIndex.value = 0

  } catch (error) {
    console.error('获取K线数据失败:', error)
  }
}

// 初始化图表
function initChart() {
  chart = echarts.init(chartRef.value)

  // 移动端特殊配置
  const isMobileDevice = isMobile()

  chart.setOption({
    title: {
      left: 'left',
      textStyle: { color: '#e5e7eb' }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' },
      backgroundColor: 'rgba(0, 0, 0, 0.9)',
      borderColor: '#333333',
      textStyle: { color: '#e5e7eb' }
    },
    backgroundColor: 'transparent',
    grid: { left: '8%', right: '5%', bottom: '15%', top: '10%' },
    xAxis: {
      type: 'category',
      data: [],
      boundaryGap: true,
      axisLabel: {
        formatter: value => value,
        color: '#9aa0a6',
        fontSize: 11
      },
      axisLine: { lineStyle: { color: '#333333' } },
      splitLine: { show: false }
    },
    yAxis: {
      scale: true,
      axisLabel: {
        color: '#9aa0a6',
        fontSize: 11,
        formatter: '{value}'
      },
      axisLine: { lineStyle: { color: '#333333' } },
      splitLine: {
        lineStyle: {
          color: '#1a1a1a',
          type: 'dashed'
        }
      }
    },
    series: [{
      name: 'K线',
      type: 'candlestick',
      data: [],
      itemStyle: {
        color: '#00ff88',
        color0: '#ff4757',
        borderColor: '#00ff88',
        borderColor0: '#ff4757'
      },
      emphasis: {
        itemStyle: {
          borderWidth: 2
        }
      }
    }],
    dataZoom: [
      {
        type: 'inside',
        start: 70,
        end: 100,
        zoomOnMouseWheel: !isMobileDevice,
        moveOnMouseMove: true,
        moveOnMouseWheel: false,
        preventDefaultMouseMove: true,
        zoomLock: false,
        throttle: isMobileDevice ? 50 : 100,
        zoomOnPinch: true,
        moveOnPinch: true
      }
    ]
  })
}

function preloadDataUntilNow() {
  const now = new Date()
  const startOfDay = new Date()
  startOfDay.setHours(0, 0, 0, 0)

  // 当前时间距离 00:00 过去了多少分钟
  const minutesSinceStart = Math.floor((now - startOfDay) / (1000 * 60))

  // 15分钟一个点，取整
  const nowIndex = Math.floor(minutesSinceStart / 15)

  // 确保有数据才更新图表
  if (fullKData.value.length > 0) {
    const option = chart.getOption()
    option.series[0].data = fullKData.value.slice(0, nowIndex)
    option.xAxis[0].data = timeLabelsAll.value.slice(0, nowIndex)
    chart.setOption(option)
    currentIndex.value = nowIndex
  } else {
    console.warn()
  }
}

// 每隔一段时间添加一个点
function startAppendingData() {
  timer = setInterval(() => {
    const now = new Date()
    const startOfDay = new Date()
    startOfDay.setHours(0, 0, 0, 0)
    const minutesSinceStart = Math.floor((now - startOfDay) / (1000 * 60))
    const shouldIndex = Math.floor(minutesSinceStart / 15)

    if (currentIndex.value <= shouldIndex && currentIndex.value < fullKData.value.length) {
      const option = chart.getOption()
      option.series[0].data.push(fullKData.value[currentIndex.value])
      option.xAxis[0].data.push(timeLabelsAll.value[currentIndex.value])
      chart.setOption(option)
      currentIndex.value++
    }
  }, 10 * 1000) // 每分钟检查一次（不用太频繁）
}

// 重新加载数据
async function reload() {
  if (timer) {
    clearInterval(timer)
    timer = null
  }

  await prepareKLineData()
  if (chart) {
    chart.dispose()
  }
  initChart()
  preloadDataUntilNow()
  startAppendingData()
  window.addEventListener('resize', handleResize)
}

// 格式化数值
const formatVolume = (vol) => {
  if (vol >= 100000000) return (vol / 100000000).toFixed(2) + '亿'
  if (vol >= 10000) return (vol / 10000).toFixed(2) + '万'
  return vol.toString()
}

const formatMarketCap = (cap) => {
  if (cap >= 100000000) return (cap / 100000000).toFixed(2) + '亿'
  if (cap >= 10000) return (cap / 10000).toFixed(2) + '万'
  return cap.toString()
}

const calculateAmplitude = () => {
  if (dayHigh.value && dayLow.value) {
    return ((parseFloat(dayHigh.value) - parseFloat(dayLow.value)) / parseFloat(dayLow.value) * 100).toFixed(2)
  }
  return '0.00'
}

const getPriceChangeClass = () => {
  const change = parseFloat(priceChange.value)
  if (change > 0) return 'positive'
  if (change < 0) return 'negative'
  return 'neutral'
}
// eslint-disable-next-line
const getPriceChangeArrow = () => {
  const change = parseFloat(priceChange.value)
  if (change > 0) return '↗'
  if (change < 0) return '↘'
  return '→'
}

// 更新价格信息
function updatePriceInfo() {
  if (fullKData.value.length > 0) {
    const latestData = fullKData.value[fullKData.value.length - 1]
    const prevData = fullKData.value.length > 1 ? fullKData.value[fullKData.value.length - 2] : latestData

    currentPrice.value = latestData[1].toFixed(2) // 收盘价
    openPrice.value = fullKData.value[0][0].toFixed(2) // 开盘价
    prevClose.value = prevData[1].toFixed(2) // 前收盘

    // 计算涨跌
    const change = parseFloat(currentPrice.value) - parseFloat(prevClose.value)
    priceChange.value = change.toFixed(2)
    priceChangePercent.value = (change / parseFloat(prevClose.value) * 100).toFixed(2)

    // 计算24小时最高最低
    const prices = fullKData.value.map(item => [item[2], item[3]]).flat() // 所有最高最低价
    dayLow.value = Math.min(...prices).toFixed(2)
    dayHigh.value = Math.max(...prices).toFixed(2)

    // 模拟其他数据更新
    volume.value = Math.floor(Math.random() * 50000000) + 10000000
    marketCap.value = Math.floor(Math.random() * 100000000000) + 50000000000

    // 计算技术指标（简化计算）
    updateTechnicalIndicators()
  }
}

// 更新技术指标
function updateTechnicalIndicators() {
  if (fullKData.value.length >= 20) {
    const prices = fullKData.value.slice(-20).map(item => item[1]) // 取最近20个收盘价

    // 计算移动平均线
    ma5.value = (prices.slice(-5).reduce((a, b) => a + b, 0) / 5).toFixed(2)
    ma10.value = (prices.slice(-10).reduce((a, b) => a + b, 0) / 10).toFixed(2)
    ma20.value = (prices.reduce((a, b) => a + b, 0) / 20).toFixed(2)

    // 简化的MACD计算
    const ema12 = calculateEMA(prices, 12)
    const ema26 = calculateEMA(prices, 26)
    const macdValue = ema12 - ema26
    macd.value = macdValue.toFixed(4)
    macdClass.value = macdValue >= 0 ? 'positive' : 'negative'
  }
}

// 计算EMA（指数移动平均）
function calculateEMA(prices, period) {
  if (prices.length < period) return prices[prices.length - 1]

  const multiplier = 2 / (period + 1)
  let ema = prices[0]

  for (let i = 1; i < prices.length; i++) {
    ema = (prices[i] * multiplier) + (ema * (1 - multiplier))
  }

  return ema
}

// 跳转到登录页面
function goToLogin() {
  router.push('/user/auth')
}

import {userStarStock} from "@/api/user/userget";
import {userCancelStarStock} from "@/api/user/userother";
// 收藏功能
async function toggleFavorite() {
  if (!hasToken.value) {
    toast.warning("请先登录")
    return
  }

  try {
    if (isFavorited.value) {
      // 取消收藏的API调用
      await userCancelStarStock(stockSymbol.value)
      isFavorited.value = false
    } else {
      // 添加收藏的API调用
      await userStarStock(stockSymbol.value)
      isFavorited.value = true
    }
  } catch (error) {
    toast.warning('操作失败，请重试')
  }
}

import {isUserStarThisStock} from "@/api/user/userget";
// 检查收藏状态
async function checkFavoriteStatus() {
  if (!hasToken.value) return

  try {
    // 检查收藏状态的API调用
    const { data } = await isUserStarThisStock(stockSymbol.value)
    isFavorited.value = data
  } catch (error) {
    console.error(error)
  }
}
// 提交委托
async function submitOrder() {
  if (!hasToken.value) {
    toast.warning("请先登录")
    return
  }

  if (!orderPrice.value || !orderAmount.value) {
    toast.warning('请填写完整信息')
    return
  }

  try {
    console.log('提交委托:', {
      type: orderType.value,
      price: orderPrice.value,
      amount: orderAmount.value,
      stockSymbol: stockSymbol.value
    })


    const pushData=ref(
        {"stockSymbol":stockSymbol.value,
          "orderAmount":orderPrice.value,
          "stockQuantity":orderAmount.value,
          "nowPrice":currentPrice.value
          }
    )

    if(orderType.value==="buy"){
      const {code,message}=await pushBuyOrder(pushData)
      if(code===200){
        toast.success('委托提交成功')
      }else throw new Error(message||"挂单失败")

      orderPrice.value = ''
      orderAmount.value = ''

      // 刷新历史委托
      loadOrderHistory()
    }else {
      const {code,message}=await pushSellOrder(pushData)
      if(code===200){
        toast.success('委托提交成功')
      }else throw new Error(message||"挂单失败")

      orderPrice.value = ''
      orderAmount.value = ''

      // 刷新历史委托
      loadOrderHistory()
    }


  } catch (error) {
    console.error('委托提交失败:', error)
  }
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取状态文本
function getStatusText(status) {
  const statusMap = {
    'ing': '待成交',
    'done': '已成交',
    'cancel': '已撤销',
  }
  return statusMap[status] || status
}
import {getUserOrderByStockSymbol} from "@/api/user/userget";
import userInfoStore from "@/stores/userInfo";
import toast from "@/utils/toast";
// 加载历史委托
async function loadOrderHistory() {
  if (!hasToken.value) return

  try {

    const {data}=await getUserOrderByStockSymbol(stockSymbol.value)
    orderHistory.value=data

  } catch (error) {
    console.error('加载历史委托失败:', error)
    orderHistory.value = []
  }
}


// 滚动到页面顶部的函数
const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    left: 0,
    behavior: 'smooth'
  })
}

// 监听路由变化，确保每次进入页面都滚动到顶部
watch(() => route.query.stockSymbol, () => {
  // 使用 nextTick 确保 DOM 更新后再滚动
  nextTick(() => {
    scrollToTop()
  })
}, { immediate: true })

const userInfo = ref({})
// 初次挂载
onMounted(async () => {
  // 滚动到页面顶部
  scrollToTop()

  // 初始化时间并设置定时更新
  updateCurrentTime()
  setInterval(updateCurrentTime, 1000)
  userInfo.value=userInfoStore().info
  accountBalance.value=userInfo.value.balance
  await prepareKLineData()


  if (fullKData.value.length > 0) {
    initChart()
    preloadDataUntilNow()
    startAppendingData()
    window.addEventListener('resize', handleResize)

    updatePriceInfo()
    loadOrderHistory()
    checkFavoriteStatus()

  } else {
    console.error('无法初始化图表：没有数据')
  }
})

// 检测是否为移动设备
function isMobile() {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
}

// 窗口大小变化时重新调整图表大小
function handleResize() {
  if (chart) {
    chart.resize()
  }
}

// 组件卸载时清理资源
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
  if (chart) {
    chart.dispose()
    chart = null
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
/* Apple风格全局样式 */
.main {
  min-height: 100vh;
  background: #000000;
  color: #e5e7eb;
  font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Display', 'SF Pro Text', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  overflow-x: hidden;
  line-height: 1.47;
}

/* 简洁过渡效果 */
.transition-base {
  transition: all 0.2s ease;
}

/* Apple风格顶部标题栏 */
.header-section {
  background: rgba(0, 0, 0, 0.9);
  backdrop-filter: blur(20px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.08);
  padding: 20px 24px;
  position: sticky;
  top: 0;
  z-index: 100;
}

.stock-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1200px;
  margin: 0 auto;
  gap: 20px;
}

.stock-info {
  display: flex;
  align-items: center;
  gap: 24px;
}

.ticker-symbol {
  font-size: 34px;
  font-weight: 700;
  margin: 0;
  color: #e5e7eb;
  letter-spacing: -0.5px;
}

.stock-subtitle {
  font-size: 17px;
  color: #9aa0a6;
  margin-top: 2px;
  font-weight: 400;
  display: flex;
  align-items: center;
  gap: 8px;
}

.market-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.market-status {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 500;
  color: #34c759;
}

.status-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #34c759;
}

.market-time {
  font-size: 13px;
  color: #9aa0a6;
  font-weight: 400;
  font-variant-numeric: tabular-nums;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 24px;
}

.quick-stats {
  display: flex;
  gap: 24px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 2px;
}

.stat-label {
  font-size: 12px;
  color: #86868b;
  font-weight: 400;
}

.stat-value {
  font-size: 15px;
  font-weight: 600;
  color: #1d1d1f;
  font-variant-numeric: tabular-nums;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

/* Apple风格按钮 */
.reload-btn, .favorite-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #1a1a1a;
  border: none;
  color: #e5e7eb;
  padding: 10px 20px;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s ease;
  min-width: 80px;
}

.reload-btn:hover, .favorite-btn:hover {
  background: #2a2a2a;
  transform: scale(0.98);
}

.favorite-btn.favorited {
  background: #2563eb;
  color: #ffffff;
}

.favorite-btn.favorited:hover {
  background: #1d4ed8;
}

/* Apple风格主要价格显示区域 */
.main-price-section {
  background: #0a0a0a;
  border-radius: 18px;
  margin: 24px;
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
  padding: 40px;
}

.primary-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 40px;
}

.current-price-large {
  display: flex;
  align-items: baseline;
  gap: 8px;
  flex-wrap: wrap;
}

.currency-symbol {
  font-size: 28px;
  color: #9aa0a6;
  font-weight: 400;
}

.price-number {
  font-size: 56px;
  font-weight: 700;
  color: #e5e7eb;
  font-variant-numeric: tabular-nums;
  letter-spacing: -1px;
}

.price-change {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 20px;
  font-weight: 600;
  margin-left: 16px;
}

.price-change.positive {
  color: #34c759;
}

.price-change.negative {
  color: #ff3b30;
}

.price-change.neutral {
  color: #9aa0a6;
}

.price-details {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 24px;
  min-width: 220px;
}

.detail-label {
  font-size: 15px;
  color: #9aa0a6;
  font-weight: 400;
}

.detail-value {
  font-size: 17px;
  color: #e5e7eb;
  font-weight: 600;
  font-variant-numeric: tabular-nums;
}

/* Apple风格价格统计网格 */
.price-stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 12px;
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.stat-card {
  background: #0a0a0a;
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 12px;
  padding: 20px;
  transition: all 0.2s ease;
}

.stat-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.35);
}

.stat-header {
  margin-bottom: 12px;
}

.stat-title {
  font-size: 13px;
  color: #9aa0a6;
  font-weight: 400;
  margin: 0;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #e5e7eb;
  margin-bottom: 8px;
  font-variant-numeric: tabular-nums;
}

.stat-value.high-price {
  color: #34c759;
}

.stat-value.low-price {
  color: #ff3b30;
}

.stat-change {
  font-size: 12px;
  font-weight: 500;
}

.stat-change.positive {
  color: #34c759;
}

.stat-change.negative {
  color: #ff3b30;
}

.stat-change.neutral {
  color: #9aa0a6;
}

.price-card {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.05) 0%, rgba(255, 255, 255, 0.02) 100%);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 16px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 16px;
  backdrop-filter: blur(20px);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.price-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  transition: all 0.3s ease;
}

.price-card:hover {
  transform: translateY(-2px);
  border-color: rgba(255, 255, 255, 0.2);
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.08) 0%, rgba(255, 255, 255, 0.04) 100%);
}

.price-card.current::before {
  background: linear-gradient(90deg, transparent, #4a90e2, transparent);
}

.price-card.low::before {
  background: linear-gradient(90deg, transparent, #e74c3c, transparent);
}

.price-card.high::before {
  background: linear-gradient(90deg, transparent, #27ae60, transparent);
}

.price-icon {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
  flex-shrink: 0;
}

.price-card.current .price-icon {
  background: linear-gradient(135deg, rgba(74, 144, 226, 0.2), rgba(74, 144, 226, 0.05));
  color: #4a90e2;
}

.price-card.low .price-icon {
  background: linear-gradient(135deg, rgba(231, 76, 60, 0.2), rgba(231, 76, 60, 0.05));
  color: #e74c3c;
}

.price-card.high .price-icon {
  background: linear-gradient(135deg, rgba(39, 174, 96, 0.2), rgba(39, 174, 96, 0.05));
  color: #27ae60;
}

.price-icon svg {
  width: 24px;
  height: 24px;
  stroke-width: 2;
}

.price-content {
  flex: 1;
}

.price-label {
  display: block;
  font-size: 13px;
  color: #888;
  margin-bottom: 4px;
  font-weight: 500;
}

.price-value {
  display: block;
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 4px;
}

.current-price {
  color: #4a90e2;
}

.low-price {
  color: #e74c3c;
}

.high-price {
  color: #27ae60;
}

.price-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
}

.trend-indicator {
  color: #27ae60;
  font-weight: bold;
}

.trend-percent {
  color: #27ae60;
  font-weight: 600;
}

/* Apple风格图表容器 */
.chart-container {
  background: #0a0a0a;
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 18px;
  margin: 24px;
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
  position: relative;
  overflow: hidden;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.08);
}

.chart-title-section h3 {
  margin: 0;
  font-size: 22px;
  font-weight: 700;
  color: #e5e7eb;
  letter-spacing: -0.5px;
}

.chart-indicators {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.indicator-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
}

.indicator-label {
  color: #888;
  font-weight: 500;
}

.indicator-value {
  font-weight: 700;
  font-family: 'Courier New', monospace;
}

.indicator-value.ma5 { color: #ff6b6b; }
.indicator-value.ma10 { color: #4ecdc4; }
.indicator-value.ma20 { color: #45b7d1; }
.indicator-value.macd.positive { color: #00ff88; }
.indicator-value.macd.negative { color: #ff4757; }

.chart-controls {
  display: flex;
  flex-direction: column;
  gap: 12px;
  align-items: flex-end;
}

.timeframe-tabs {
  display: flex;
  gap: 4px;
}

.chart-tools {
  display: flex;
  gap: 8px;
}

.tool-btn {
  width: 32px;
  height: 32px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  color: #888;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.tool-btn:hover {
  background: rgba(0, 150, 255, 0.1);
  border-color: rgba(0, 150, 255, 0.3);
  color: #0099ff;
}

.tool-btn svg {
  width: 16px;
  height: 16px;
  stroke-width: 2;
}

.time-btn {
  padding: 8px 16px;
  background: #1a1a1a;
  border: none;
  color: #9aa0a6;
  border-radius: 12px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.time-btn.active {
  background: #333333;
  color: #ffffff;
}

.time-btn:hover:not(.active) {
  background: #2a2a2a;
  color: #e5e7eb;
}

.k-chart {
  height: 400px;
  width: 100%;
  touch-action: pan-x pan-y;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.k-chart { position: relative; }

.chart-overlay {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 2;
  pointer-events: none;
}

.market-status {
  background: rgba(16, 185, 129, 0.12);
  border: 1px solid rgba(16, 185, 129, 0.25);
  border-radius: 8px;
  padding: 6px 12px;
  backdrop-filter: blur(10px);
}

.status-text {
  font-size: 12px;
  font-weight: 500;
  color: #10b981;
}

/* 保持脉冲动画用于状态指示器 */
@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

/* Apple风格交易区域 */
.trading-section {
  background: #0a0a0a;
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 18px;
  margin: 24px;
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.08);
}

.header-left h3 {
  margin: 0;
  font-size: 22px;
  font-weight: 700;
  color: #e5e7eb;
  letter-spacing: -0.5px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.account-balance {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #1a1a1a;
  border-radius: 12px;
  padding: 8px 16px;
}

.balance-label {
  font-size: 13px;
  color: #9aa0a6;
  font-weight: 400;
}

.balance-amount {
  font-size: 15px;
  font-weight: 600;
  color: #e5e7eb;
  font-variant-numeric: tabular-nums;
}

.toolbar-tabs {
  display: flex;
  background: #1a1a1a;
  border-radius: 12px;
  margin: 12px 24px;
  padding: 4px;
}

.tab-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px 20px;
  border: none;
  background: transparent;
  cursor: pointer;
  font-size: 15px;
  font-weight: 500;
  color: #9aa0a6;
  transition: all 0.2s ease;
  border-radius: 8px;
}

.tab-btn.active {
  color: #e5e7eb;
  background: #0a0a0a;
  box-shadow: none;
}

.tab-btn:hover:not(.active) {
  color: #e5e7eb;
}

.tab-btn svg {
  width: 18px;
  height: 18px;
  stroke-width: 2;
  flex-shrink: 0;
}

.panel-content {
  padding: 32px;
}

/* 登录提示 */
.login-prompt {
  text-align: center;
  padding: 60px 20px;
}

.login-icon {
  width: 64px;
  height: 64px;
  margin: 0 auto 20px;
  background: linear-gradient(135deg, rgba(74, 144, 226, 0.2), rgba(74, 144, 226, 0.05));
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #4a90e2;
}

.login-icon svg {
  width: 28px;
  height: 28px;
  stroke-width: 2;
}

.login-prompt h3 {
  margin: 0 0 12px 0;
  font-size: 20px;
  font-weight: 600;
  color: #ffffff;
}

.login-prompt p {
  margin: 0 0 24px 0;
  color: #888;
  font-size: 14px;
}

.login-btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  background: linear-gradient(135deg, #4a90e2, #357abd);
  color: #ffffff;
  border: none;
  padding: 14px 28px;
  border-radius: 12px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.login-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(74, 144, 226, 0.3);
}

.login-btn svg {
  width: 16px;
  height: 16px;
  stroke-width: 2.5;
}

/* 交易表单 */
.order-form {
  display: flex;
  flex-direction: column;
  gap: 28px;
}

.trade-type-section h4,
.trade-inputs-section h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #ffffff;
}

.order-type {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.order-type label {
  display: block;
  cursor: pointer;
  border: 2px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 0;
  transition: all 0.3s ease;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.02);
}

.order-type label:hover {
  border-color: rgba(255, 255, 255, 0.2);
  background: rgba(255, 255, 255, 0.05);
}

.order-type label.active {
  border-color: #4a90e2;
  background: rgba(74, 144, 226, 0.05);
}

.order-type input[type="radio"] {
  display: none;
}

.radio-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  padding: 20px;
  color: #888;
  font-weight: 500;
  transition: all 0.3s ease;
}

.order-type label.active .radio-content {
  color: #4a90e2;
}

.radio-content svg {
  width: 20px;
  height: 20px;
  stroke-width: 2;
}

.order-inputs {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.input-group label {
  font-size: 14px;
  font-weight: 500;
  color: #ccc;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-prefix {
  position: absolute;
  left: 12px;
  color: #888;
  font-size: 14px;
  font-weight: 500;
  pointer-events: none;
  z-index: 2;
}

.input-suffix {
  position: absolute;
  right: 12px;
  color: #888;
  font-size: 14px;
  font-weight: 500;
  pointer-events: none;
  z-index: 2;
}

.input-group input {
  width: 100%;
  padding: 14px 16px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  background: rgba(255, 255, 255, 0.05);
  color: #fff;
  font-size: 14px;
  border-radius: 10px;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: textfield;
}

.input-group input::-webkit-outer-spin-button,
.input-group input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

.input-wrapper:has(.input-prefix) input {
  padding-left: 36px;
}

.input-wrapper:has(.input-suffix) input {
  padding-right: 36px;
}

.input-group input:focus {
  outline: none;
  border-color: #4a90e2;
  background: rgba(255, 255, 255, 0.08);
  box-shadow: 0 0 0 3px rgba(74, 144, 226, 0.1);
}

.quick-fill {
  position: absolute;
  right: 8px;
  background: rgba(74, 144, 226, 0.1);
  border: 1px solid rgba(74, 144, 226, 0.3);
  color: #4a90e2;
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 3;
}

.quick-fill:hover {
  background: rgba(74, 144, 226, 0.2);
}

.order-summary {
  background: rgba(255, 255, 255, 0.03);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 16px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  font-size: 14px;
}

.summary-row:not(:last-child) {
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}

.summary-value {
  font-weight: 600;
  color: #ffffff;
}

.submit-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  padding: 18px;
  border: none;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  border-radius: 12px;
  transition: all 0.3s ease;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.submit-btn svg {
  width: 20px;
  height: 20px;
  stroke-width: 2.5;
}

.submit-btn.buy {
  background: linear-gradient(135deg, #27ae60, #219a52);
  color: #ffffff;
}

.submit-btn.sell {
  background: linear-gradient(135deg, #e74c3c, #c0392b);
  color: #ffffff;
}

.submit-btn:hover {
  transform: translateY(-2px);
}

.submit-btn.buy:hover {
  box-shadow: 0 8px 25px rgba(39, 174, 96, 0.4);
}

.submit-btn.sell:hover {
  box-shadow: 0 8px 25px rgba(231, 76, 60, 0.4);
}

/* 历史委托 */
.history-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.history-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #ffffff;
}

.filter-select {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  color: #fff;
  padding: 8px 12px;
  border-radius: 8px;
  font-size: 12px;
  cursor: pointer;
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6,9 12,15 18,9'%3e%3c/polyline%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right 8px center;
  background-size: 16px;
  padding-right: 32px;
}

.filter-select option {
  background: #1a1a1a;
  color: #e5e7eb;
  padding: 8px 12px;
}

.filter-select:focus {
  outline: none;
  border-color: rgba(255, 255, 255, 0.3);
  box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.1);
}

.filter-select:hover {
  background: rgba(255, 255, 255, 0.08);
  border-color: rgba(255, 255, 255, 0.2);
}

.empty-history {
  text-align: center;
  padding: 60px 20px;
}

.empty-icon {
  width: 64px;
  height: 64px;
  margin: 0 auto 20px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
}

.empty-icon svg {
  width: 28px;
  height: 28px;
  stroke-width: 2;
}

.empty-history h4 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #ccc;
}

.empty-history p {
  margin: 0;
  color: #888;
  font-size: 14px;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: rgba(255, 255, 255, 0.03);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  transition: all 0.3s ease;
}

.history-item:hover {
  background: rgba(255, 255, 255, 0.05);
  border-color: rgba(255, 255, 255, 0.2);
  transform: translateY(-1px);
}

.order-main {
  display: flex;
  align-items: center;
  gap: 16px;
}

.order-type-badge {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 8px;
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
}

.order-type-badge.buy {
  background: rgba(39, 174, 96, 0.1);
  color: #27ae60;
  border: 1px solid rgba(39, 174, 96, 0.2);
}

.order-type-badge.sell {
  background: rgba(231, 76, 60, 0.1);
  color: #e74c3c;
  border: 1px solid rgba(231, 76, 60, 0.2);
}

.order-type-badge svg {
  width: 14px;
  height: 14px;
  stroke-width: 2.5;
}

.order-details {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.order-symbol {
  font-weight: 600;
  color: #ffffff;
  font-size: 14px;
}

.order-price-amount {
  display: flex;
  align-items: center;
  gap: 12px;
}

.order-price {
  font-weight: 600;
  color: #ffffff;
  font-size: 16px;
}

.order-amount {
  color: #888;
  font-size: 14px;
}

.order-total {
  color: #666;
  font-size: 12px;
}

.order-time {
  color: #666;
  font-size: 12px;
}

.order-status {
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
}

.order-status.done {
  background: rgba(39, 174, 96, 0.1);
  color: #27ae60;
}

.order-status.ing {
  background: rgba(241, 196, 15, 0.1);
  color: #f1c40f;
}

.order-status.cancel {
  background: rgba(231, 76, 60, 0.1);
  color: #e74c3c;
}

/* 专业响应式设计 */
@media (max-width: 1200px) {
  .stock-header {
    gap: 16px;
  }

  .quick-stats {
    gap: 12px;
  }

  .primary-price {
    flex-direction: column;
    align-items: flex-start;
    gap: 20px;
  }

  .price-stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  }
}

@media (max-width: 768px) {
  .stock-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .stock-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .header-actions {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    width: 100%;
  }

  .quick-stats {
    width: 100%;
    justify-content: space-between;
  }

  .ticker-symbol {
    font-size: 28px;
  }

  .price-number {
    font-size: 36px;
  }

  .price-stats-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
    padding: 16px;
  }

  .chart-container,
  .trading-section {
    margin: 16px;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .header-right {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .chart-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .chart-indicators {
    gap: 12px;
  }

  .chart-controls {
    align-items: flex-start;
    gap: 8px;
  }

  .chart-overlay {
    top: 60px;
    right: 16px;
  }

  .panel-content {
    padding: 20px;
  }

  .order-inputs {
    grid-template-columns: 1fr;
  }

  .order-type {
    grid-template-columns: 1fr;
  }

  .history-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .history-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
}

@media (max-width: 480px) {
  .price-card {
    padding: 16px;
  }

  .price-value {
    font-size: 20px;
  }

  .stock-title h1 {
    font-size: 24px;
  }

  .k-chart {
    height: 300px;
  }
}
</style>